import { request as umiRequest, history, useModel } from 'umi';
import { message } from 'antd';
import { setRefreshToken } from '@/services/admin/common/api';
import { setLocalStorage, removeLocalStorage, getLocalStorage } from '@/utils/LocalStorage';
import { stringify } from 'querystring';

//, useModel
// eslint-disable-next-line react-hooks/rules-of-hooks
//
interface Options {
  prefix?: string;
  method?: string;
  headers?: any;
  timeout?: number;
  timeoutMessage?: string;
  params?: any;
  data?: any;
  errorHandler?: (error: any) => void;
}
const clearExit = async () => {
  await removeLocalStorage('token');
  await removeLocalStorage('expires_in');
  await removeLocalStorage('token_type');
  const { query = {}, search, pathname } = history.location;
  const { redirect } = query;
  if (window.location.pathname !== '/login' && !redirect) {
    history.replace({
      pathname: '/login',
      search: stringify({
        redirect: pathname + search,
      }),
    });
  }
};
const refreshToken = async (url: string, options: any) => {
  const res = await setRefreshToken();
  if (res.status === 20000) {
    await setLocalStorage('token', res.data.token);
    await setLocalStorage('expires_in', res.data.expires_in);
    await setLocalStorage('token_type', res.data.token_type);
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    return await request(url, options);
  } else {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const { setInitialState } = useModel('@@initialState');
    setInitialState((s: any) => ({ ...s, currentUser: undefined }));
    return await clearExit();
  }
};
const request = async (url: string, options: Options = {}) => {
  const token_type = await getLocalStorage('token_type');
  const token = await getLocalStorage('token');
  const { pathname } = history.location;
  const umiOptions: Options = {
    prefix: PREFIX, // 前缀, 一般用于覆盖统一设置的 prefix
    method: options.method || 'get', // 请求方式
    headers: {
      // 'Content-Type': 'application/json',
      apikey: API_KEY, // apikey
      Authorization: token_type + ' ' + token, // token
      pathname: pathname,
      ...options.headers,
    },
    timeout: options.timeout || TIMEOUT, // 超时时长, 默认毫秒, 写操作慎用
    timeoutMessage: options.timeoutMessage || '请求超时，请重试...', //超时可自定义提示文案, 需先定义 timeout
  };
  if (umiOptions.method === 'get') {
    if (options.params && options.params.current) {
      options.params.page = options.params.current;
      delete options.params.current;
    }
    if (options.params && options.params.pageSize) {
      options.params.limit = options.params.pageSize;
      delete options.params.pageSize;
    }
    umiOptions.params = options.params || {}; //url 请求参数
  } else {
    umiOptions.data = options.data || {}; // 提交的数据
  }
  umiOptions.errorHandler = async (error: { data: any }) => {
    const { data } = error;
    if (data.status === 70007) {
      history.replace({
        pathname: '/403',
      });
      return;
    }
    if (data.status === 40000) {
      message.error(data.message);
      return data;
    }
    if (data.status === 70004) {
      return await refreshToken(url, options);
    }
    if (
      data.status === 70002 ||
      data.status === 70003 ||
      data.status === 70005 ||
      data.status === 70006
    ) {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const { setInitialState } = useModel('@@initialState');
      setInitialState((s: any) => ({ ...s, currentUser: undefined }));
    }
  };
  return await umiRequest(url, umiOptions);
};
export { request, clearExit };
